import { querySmsFlow } from '../services/api';

export default {
  namespace: 'flow',

  state: {
    list: [],
    pagination: {},
  },

  effects: {
    *fetch({ payload }, { call, put }) {
      const response = yield call(querySmsFlow, payload);
      let dataSource = response.simUsageTrend;
      if (payload) {
        if (payload.sorter) {
          const s = payload.sorter.split('_');
          if (s[1] === 'descend') {
            dataSource = dataSource.sort((prev, next) => method(s[0], next[s[0]], prev[s[0]]));
          } else {
            dataSource = dataSource.sort((prev, next) => method(s[0], prev[s[0]], next[s[0]]));
          }
        }

        let pageSize = 10;
        if (payload.pageSize) {
          pageSize = payload.pageSize * 1;
        }

        const result = {
          list: Array.isArray(response.simUsageTrend) ? dataSource : [],
          pagination: {
            total: dataSource.length ? dataSource.length : 0,
            pageSize,
            current: parseInt(payload.currentPage, 10) || 1,
          },
        };

        //console.log('log', result);
        yield put({
          type: 'save',
          payload: result,
        });
      }
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        list: action.payload.list,
        pagination: action.payload.pagination,
      };
    },
  },
};
